import React, { useEffect, useState } from 'react'
import {
  Space,
  Table,
  Card,
  Button,
  Popconfirm,
  message,
  Form,
  Modal,
  Input,
  Upload,
  Image
} from 'antd'
import { baseURL } from '@/http/request'
import { FolderOpenOutlined } from '@ant-design/icons'
import { iconsEmpty, iconsList } from '@/http/api/resource'
let _id = ''
const App = React.forwardRef((props, ref) => {
  const [messageApi, contextHolder] = message.useMessage()
  const handleChildMethod = () => {
    getList()
  }

  React.useImperativeHandle(ref, () => ({
    handleChildMethod
  }))
  const columns = [
    {
      title: '图标名称',
      dataIndex: 'name',
      key: 'name',
      align: 'center'
    },
    {
      title: '图标（选中状态）',
      dataIndex: 'selectImg',
      align: 'center',
      key: 'selectImg',
      render: (selectImg) => (
        <Image
          width={60}
          height={60}
          src={selectImg}
          fallback=""
        />
      )
    },
    {
      title: '图标（未选中状态）',
      dataIndex: 'unSelectImg',
      align: 'center',
      key: 'unSelectImg',
      render: (unSelectImg) => (
        <Image
          width={60}
          height={60}
          src={unSelectImg}
          fallback=""
        />
      )
    },
    {
      title: '底图',
      dataIndex: 'backImg',
      align: 'center',
      key: 'backImg',
      render: (backImg) => (
        <Image
          width={60}
          height={60}
          src={backImg}
          fallback=""
        />
      )
    },
    {
      title: '备注',
      dataIndex: 'remark',
      align: 'center',
      key: 'remark'
    },
    {
      title: '操作',
      key: 'action',
      align: 'center',
      render: (data) => (
        <Space size="middle">
          <Button
            type="primary"
            onClick={() => {
              form.setFieldsValue(data)
              setIsModalOpen(true)
              _id = data._id
            }}
          >
            编辑
          </Button>
          <Popconfirm
            title="清空"
            description="确定清空吗?"
            placement="top"
            onConfirm={() => {
              iconsEmptyFn(data)
            }}
            onCancel={() => {
              message.error('取消清空')
            }}
            okText="是"
            cancelText="不"
          >
            <Button type="primary" danger>
              清空
            </Button>
          </Popconfirm>
        </Space>
      )
    }
  ]
  const [isModalOpen, setIsModalOpen] = useState(false)
  const [tableList, settableList] = useState([])
  const [form] = Form.useForm()
  const getList = async () => {
    let dataList = []
    let id = localStorage.getItem('appid')
    const res = await iconsList({ id })
    res.data.res.forEach((item) => {
      item.key = item._id
      if (item.type == 0) {
        dataList.push(item)
      }
    })
    settableList(dataList)
  }
  const onFinish = async (data) => {
    data._id = _id
    data.selectImg = data.selectImg.fileList[0]?.response.image_url
    data.unSelectImg = data.unSelectImg.fileList[0]?.response.image_url
    data.backImg = data.backImg.fileList[0]?.response.image_url
    const res = await iconsEmpty(data)
    getList()
    messageApi.success(res.data.messge)
    setIsModalOpen(false)
  }
  const iconsEmptyFn = async (value) => {
    let data = {
      _id: value._id,
      name: '',
      selectImg: '',
      unSelectImg: '',
      backImg: '',
      remark: ''
    }

    const res = await iconsEmpty(data)
    getList()
    setIsModalOpen(false)
    messageApi.success(res.data.messge)
  }
  return (
    <Card>
      <div className="headerButton">
        <div className="title">首页图标</div>
      </div>
      <Table
        pagination={false}
        bordered
        columns={columns}
        dataSource={tableList}
      />
      <Modal
        title="添加"
        footer={[]}
        open={isModalOpen}
        onCancel={() => {
          setIsModalOpen(false)
          form.resetFields()
        }}
      >
        <Form
          labelCol={{
            span: 5
          }}
          wrapperCol={{
            span: 14
          }}
          layout="horizontal"
          style={{
            maxWidth: 800
          }}
          form={form}
          onFinish={onFinish}
        >
          <Form.Item
            label="图片名称"
            name="name"
            rules={[
              {
                required: true,
                message: '请输入名称'
              }
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="图片选中"
            name="selectImg"
            rules={[
              {
                required: true,
                message: '请选择图片'
              }
            ]}
          >
            <Upload
              accept=".jpg,.png"
              maxCount={1}
              action={baseURL + 'api/uploadAvatar'}
            >
              <Input placeholder="请选择图片" suffix={<FolderOpenOutlined />} />
            </Upload>
          </Form.Item>
          <Form.Item
            label="图片未选中"
            name="unSelectImg"
            rules={[
              {
                required: true,
                message: '请选择图片'
              }
            ]}
          >
            <Upload
              accept=".jpg,.png"
              maxCount={1}
              action={baseURL + 'api/uploadAvatar'}
            >
              <Input placeholder="请选择图片" suffix={<FolderOpenOutlined />} />
            </Upload>
          </Form.Item>
          <Form.Item
            label="底图"
            name="backImg"
            rules={[
              {
                required: true,
                message: '请选择图片'
              }
            ]}
          >
            <Upload
              accept=".jpg,.png"
              maxCount={1}
              action={baseURL + 'api/uploadAvatar'}
            >
              <Input placeholder="请选择图片" suffix={<FolderOpenOutlined />} />
            </Upload>
          </Form.Item>
          <Form.Item
            label="图片备注"
            name="remark"
            rules={[
              {
                required: true,
                message: '请输入备注'
              }
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            wrapperCol={{
              offset: 6,
              span: 16
            }}
          >
            <Button type="primary" htmlType="submit">
              确定
            </Button>
            <Button
              style={{ marginLeft: '10px' }}
              type="primary"
              onClick={() => {
                form.resetFields()
                setIsModalOpen(false)
              }}
            >
              取消
            </Button>
          </Form.Item>
        </Form>
      </Modal>
      {contextHolder}
    </Card>
  )
})
export default App
